
let product

// 获取商品id
function getProductId() {
    let str = location.search
    let id = str.split('=')[1]
    console.log(id);
    return id
}

// 获取商品详情
function getProductDetail() {
	let id = getProductId()
	requestGoodsDetail(id).then(res => {
		res = res.params
        product = res.resultInfo // 添加购物车使用
        console.log(res)
		console.log(product)
		showProductDetail(product)
	})
}

// 动态渲染数据
function showProductDetail(product) {
    let str = `<div class="container" id="glass1">
    <div class="left-wraper">
        <div class="m-left">
            <img src="${product.image}" alt="show1" />
            <!-- 遮罩层 -->
            <div class="mask"></div>
        </div>
        <ul>
            <li class="active"><img src="${product.list[0]}" alt="small1" /></li>
            <li><img src="${product.list[1]}" alt="small2" /></li>
            <li><img src="${product.list[2]}" alt="small3" /></li>
            <li><img src="${product.list[3]}" alt="small4" /></li>
        </ul>
    </div>

    <!-- 放大镜 -->
    <div class="right-wraper">
        <img src="${product.picture}" alt="big1" />
    </div>
</div>`

    const detailWraper = document.querySelector('.box')
    detailWraper.innerHTML = str
    
    // 动态渲染数据后，操作放大镜节点
    let glass = new Glass('#glass1')
    glass.setScale()
    glass.onGlass()
    glass.onTab(product)

}

// 查看购物车
function bindCart() {
	const lookCart = document.querySelector('.look_cart')
	const addCart = document.querySelector('.add_cart')

	lookCart.addEventListener('click', function () {
		location.href = './cart.html'
	})
	// 添加购物车
	addCart.addEventListener('click', function () {
		// 1. 获取原来购物车数组
		let cartList = localStorage.getItem('CART-LIST') || '[]'
		cartList = JSON.parse(cartList)

		// 1.1 判断商品是否已经加入购物车
		let oldProduct = cartList.find(item => item.id == product.id)
		if (oldProduct) {
			oldProduct.num++ // 商品存在数量加一
		} else {
			// 2. 添加商品
			let newProduct = {
				id: product.id,
				name: product.title,
				url: product.image,
                originPrice: product.originPrice,
                price:product.price,
				saleNum: 0,
				state: false,
			}
			cartList.push(newProduct)
		}

		//3.持久存储
		localStorage.setItem('CART-LIST', JSON.stringify(cartList))
		alert('保存成功!')
	})
}

// getProductDetail()
bindCart()